﻿using Calculator;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;

namespace Calculator
{
    public partial class MainWindow : Window
    {
        private List<(string Expression, string Result)> history = new List<(string, string)>(); // 历史记录
        private int historyIndex = -1; // 当前历史记录位置
        private string lastValidResult = "0"; // 上一个有效结果
        private bool isLastActionEquals = false; // 是否上一次操作为 "="

        public MainWindow()
        {
            InitializeComponent();
        }

        // 实时更新输出结果
        private void InputBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (isLastActionEquals) return; // 如果上一次是 "=", 忽略实时更新

            string input = InputBox.Text;

            // 检查并清理多余运算符
            input = CleanInput(input);

            // 更新输入框内容（移除多余运算符）
            InputBox.Text = input;
            InputBox.CaretIndex = input.Length; // 保证光标位置正确

            // 如果输入为空或只有运算符，则显示上一次有效结果
            if (string.IsNullOrWhiteSpace(input) || EndsWithOperator(input))
            {
                OutputBox.Text = lastValidResult;
                return;
            }

            try
            {
                // 专门处理 ln 和 √ 的实时计算
                if (input.Contains("ln(") || input.Contains("√("))
                {
                    string processedInput = ProcessAdvancedOperations(input); // 替换高级运算
                    var result = new DataTable().Compute(processedInput, null);
                    lastValidResult = result.ToString();
                    OutputBox.Text = lastValidResult; // 实时更新结果
                }
                else
                {
                    // 其他情况下的普通表达式处理
                    string processedInput = ProcessAdvancedOperations(input); // 替换高级运算
                    var result = new DataTable().Compute(processedInput, null);
                    lastValidResult = result.ToString();
                    OutputBox.Text = lastValidResult;
                }
            }
            catch
            {
                // 输入非法时保持上一个结果
                OutputBox.Text = lastValidResult;
            }
        }

        // 数字和小数点输入
        private void Number_Click(object sender, RoutedEventArgs e)
        {
            string input = ((Button)sender).Content.ToString();

            // 如果上一次操作是 "=", 开始新的表达式
            if (isLastActionEquals)
            {
                InputBox.Clear();
                isLastActionEquals = false;
            }

            InputBox.Text += input;
            InputBox.CaretIndex = InputBox.Text.Length; // 光标移动到末尾
        }

        // 操作符输入
        private void Operator_Click(object sender, RoutedEventArgs e)
        {
            string operatorSymbol = ((Button)sender).Content.ToString();

            // 如果上一次操作是 "=", 继续运算
            if (isLastActionEquals)
            {
                InputBox.Text = lastValidResult + " " + operatorSymbol + " ";
                isLastActionEquals = false;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(InputBox.Text))
                {
                    // 去除末尾的多余运算符（只保留一个）
                    string input = InputBox.Text.TrimEnd();

                    // 检测末尾是否为运算符
                    if (EndsWithOperator(input))
                    {
                        // 替换末尾运算符为新的
                        InputBox.Text = input.Substring(0, input.Length - 1) + operatorSymbol + " ";
                    }
                    else
                    {
                        // 否则正常追加运算符
                        InputBox.Text += " " + operatorSymbol + " ";
                    }
                }
            }

            InputBox.CaretIndex = InputBox.Text.Length; // 光标移动到末尾
        }

        // 等号按钮计算结果并记录历史
        private void Equals_Click(object sender, RoutedEventArgs e)
        {
            if (isLastActionEquals) return;

            try
            {
                string input = InputBox.Text;

                // 自动闭合未完成的括号
                int openBrackets = input.Count(c => c == '(');
                int closeBrackets = input.Count(c => c == ')');
                if (openBrackets > closeBrackets)
                {
                    input += new string(')', openBrackets - closeBrackets);
                }

                string processedInput = ProcessAdvancedOperations(input);
                var result = new DataTable().Compute(processedInput, null);

                // 显示结果
                string fullExpression = $"{input} = {result}";
                InputBox.Text = fullExpression;
                OutputBox.Text = result.ToString();

                // 保存历史记录
                history.Add((fullExpression, result.ToString()));
                historyIndex = history.Count - 1;
                lastValidResult = result.ToString();

                isLastActionEquals = true;
            }
            catch
            {
                OutputBox.Text = "错误";
            }
        }

        // 开方运算
        private void Sqrt_Click(object sender, RoutedEventArgs e)
        {
            InputBox.Text += " √(";
            InputBox.CaretIndex = InputBox.Text.Length;
        }

        // 幂运算
        private void Power_Click(object sender, RoutedEventArgs e)
        {
            InputBox.Text += " ^ ";
            InputBox.CaretIndex = InputBox.Text.Length;
        }

        // 对数运算 (ln)
        private void Log_Click(object sender, RoutedEventArgs e)
        {
            InputBox.Text += " ln(";
            InputBox.CaretIndex = InputBox.Text.Length;
        }

        // 清除按钮
        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            InputBox.Clear();
            OutputBox.Clear();
            lastValidResult = "0"; // 重置最后有效结果
            isLastActionEquals = false; // 重置状态
        }

        // 删除按钮
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (InputBox.Text.Length > 0)
            {
                int caretPosition = InputBox.CaretIndex; // 获取当前光标位置

                if (caretPosition > 0)
                {
                    // 检查光标前一个字符是否是空格
                    if (caretPosition > 1 && InputBox.Text[caretPosition - 2] == ' ')
                    {
                        // 删除两个字符（空格和前一个字符）
                        InputBox.Text = InputBox.Text.Remove(caretPosition - 2, 2);
                        InputBox.CaretIndex = caretPosition - 2;
                    }
                    else
                    {
                        // 删除一个字符
                        InputBox.Text = InputBox.Text.Remove(caretPosition - 1, 1);
                        InputBox.CaretIndex = caretPosition - 1;
                    }
                }

                isLastActionEquals = false; // 重置状态
            }
        }

        // 前进历史记录
        private void Forward_Click(object sender, RoutedEventArgs e)
        {
            if (historyIndex < history.Count - 1)
            {
                historyIndex++;
                UpdateHistoryDisplay();
            }
        }

        // 后退历史记录
        private void Back_Click(object sender, RoutedEventArgs e)
        {
            if (historyIndex > 0)
            {
                historyIndex--;
                UpdateHistoryDisplay();
            }
        }

        // 更新历史记录的输入和输出显示
        private void UpdateHistoryDisplay()
        {
            if (historyIndex >= 0 && historyIndex < history.Count)
            {
                var (expression, result) = history[historyIndex];
                InputBox.Text = expression;
                OutputBox.Text = result;
            }
        }

        // 判断输入是否以运算符结尾
        private bool EndsWithOperator(string input)
        {
            char[] operators = { '+', '-', '*', '/', '^' };

            // 去除末尾空格后检测最后一个字符
            input = input.TrimEnd();
            return !string.IsNullOrEmpty(input) && operators.Contains(input.Last());
        }

        // 清理输入中的多余运算符
        private string CleanInput(string input)
        {
            if (string.IsNullOrWhiteSpace(input)) return "";

            // 移除连续的多余运算符，保留最后一个
            char[] operators = { '+', '-', '*', '/', '^' };
            for (int i = 1; i < input.Length; i++)
            {
                if (operators.Contains(input[i]) && operators.Contains(input[i - 1]))
                {
                    input = input.Remove(i - 1, 1); // 移除前一个运算符
                    i--; // 调整索引
                }
            }

            return input;
        }

        // 替换高级运算 (幂次、ln、√)
        private string ProcessAdvancedOperations(string input)
        {
            string processedInput = input;

            // 替换 ln(x) 为 Math.Log(x)
            processedInput = Regex.Replace(processedInput, @"ln\s*\(([^()]+)\)", match =>
            {
                string innerExpression = match.Groups[1].Value;
                double result = double.Parse(new DataTable().Compute(innerExpression, null).ToString());
                return Math.Log(result).ToString();
            });

            // 替换 √x 为 Math.Sqrt(x)
            processedInput = Regex.Replace(processedInput, @"√\s*\(([^()]+)\)", match =>
            {
                string innerExpression = match.Groups[1].Value;
                double result = double.Parse(new DataTable().Compute(innerExpression, null).ToString());
                return Math.Sqrt(result).ToString();
            });

            // 替换 x ^ y 为 Math.Pow(x, y)
            processedInput = Regex.Replace(processedInput, @"(\d+(\.\d+)?)\s*\^\s*(\d+(\.\d+)?)", match =>
            {
                double baseNum = double.Parse(match.Groups[1].Value);
                double exponent = double.Parse(match.Groups[3].Value);
                return Math.Pow(baseNum, exponent).ToString();
            });

            return processedInput;
        }

        /// <summary>
        /// 三角函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TrigFunction_Click(object sender, RoutedEventArgs e)
        {
            // 打开三角函数子窗口
            //TrigFunctionWindow trigWindow = new TrigFunctionWindow();
            //trigWindow.Owner = this; // 设置主窗口为子窗口的拥有者
            //trigWindow.Show(); // 显示子窗口
        }

        private void Advance_Click(object sender, RoutedEventArgs e)
        {
            Advance advance = new Advance();
            advance.Owner = this;
            advance.Show();

        }
    }
}
